<?php
/**
 * Created by PhpStorm.
 * User: xding
 * Date: 15/10/28
 * Time: 上午10:21
 */

class Medias_model extends CI_Model {

    /**
     * @var array 上传文件分类数组
     */
    private $_path = array (
        'image' => UPLOAD_PATH . 'images' . DIRECTORY_SEPARATOR,
        'file'  => UPLOAD_PATH . 'files' . DIRECTORY_SEPARATOR,
        'video' => UPLOAD_PATH . 'videos' . DIRECTORY_SEPARATOR,
        'all'   => UPLOAD_PATH
    );

    private $_type = array (
        'image' => array( 'jpg','jpeg','png','gif','svg' ),
        'file'  => array( 'doc','docx','xls','xlsx','txt','zip','ppt','pptx','wps','dps','et' ),
        'video' => array( 'mp3','mp4','flv' )
    );

    // 媒体可以排序的字段
    private $_sort_key = array ('media_name','media_create_time','media_size');
    private $sort_key  = NULL;
    private $sort_type = NULL;

    // 所有媒体对象组成的数组
    private $media_arr      = NULL;
    // media 分类数组 like array( 'image' => array(...) )
    private $media_arr2type = NULL;
    // initialize status
    private $init_status    = 0;

    // 默认查询所有文件
    private $query_type = 'all';

    // 开始位置，用于分页
    private $start = 0;
    // 每页默认记录数
    private $rows  = 12;


    /**
     * 构造函数
     */
    public function __construct() {
        parent::__construct();
        // Load file helper
        $this->load->helper('file');
    }

    /**
     * 初始化数据
     *
     * @param $path
     * @return $this
     * @throws Exception
     */
    public function initialize( $path ) {
        $this->media_arr   = $this->get_media_list($path);
        $this->init_status = 1;

        return $this;
    }


    /**
     * 更具指定字段对文件数据进行排序
     *
     * @param $sort_key
     * @param string $sort_type
     * @return $this
     * @throws Exception
     */
    public function sort($sort_key,$sort_type = 'ASC') {

        if ( !$this->init_status )
        {
            throw new Exception('fetal error: please execute initialize method before');
        }

        if ( !in_array($sort_key,$this->_sort_key) )
        {
            throw new Exception ('fetal error: sort fields is not exists in $_sort_key array');
        }

        // 转换为全部大写
        $sort_type = strtoupper($sort_type);

        // 如果排序过，则直接返回
        if ( $sort_key === $this->sort_key && $sort_type === $this->sort_type )
        {
            return $this;
        }

        $this->sort_key = $sort_key;
        $this->sort_type = $sort_type;

        // 排序
        usort($this->media_arr, function($a,$b){
            if ( $a->{$this->sort_key} === $b->{$this->sort_key} )
                return 0;
            if ( 'ASC' === $this->sort_type )
                return ($a->{$this->sort_key} > $b->{$this->sort_key}) ? 1 : -1;
            return ($a->{$this->sort_key} > $b->{$this->sort_key} ) ? -1 : 1;
        });

        return $this;
    }




    /**
     * 设置需要查询的文件类型
     *
     * @param $type
     * @return $this
     * @throws Exception
     */
    public function set_query_type( $type ) {

        if ( !$this->init_status )
        {
            throw new Exception('fetal error: please execute initialize method before');
        }

        if ( !$type )
        {
            throw new Exception('fetal error: params can not empty');
        }

        switch ( $type )
        {
            case 'image':
            case 'file':
            case 'video':
                $this->query_type = $type;
                break;
            default :
                $this->query_type = 'all';
        }

        return $this;
    }

    /**
     * 做分页处理
     *
     * @param $start
     * @param $rows
     * @return $this
     */
    public function limit($start,$rows) {
        if ( ! intval($start) ) return $this;
        $this->start = intval($start);
        $this->rows  = intval($rows);
        return $this;
    }


    /**
     * @return int
     * @throws Exception
     */
    public function get_media_count() {
        if ( !$this->init_status )
        {
            throw new Exception('fetal error: please execute initialize method before');
        }

        if ( 'all' === $this->query_type )
        {
            return count($this->media_arr);
        }

        return count($this->media_arr2type[$this->query_type]);
    }

    /**
     * 获取数据集合
     *
     * @return null
     * @throws Exception
     */
    public function get () {
        if ( !$this->init_status )
        {
            throw new Exception('fetal error: please execute initialize method before');
        }

        if ( 'all' === $this->query_type )
        {
            return $this->_get_by_limit($this->media_arr);
        }

        $this->_get_by_type($this->query_type);
        return $this->_get_by_limit($this->media_arr2type[$this->query_type]);
    }

    private function _get_by_limit(&$media_arr) {

        if ( !$this->start ) return $media_arr;

        $count = count($media_arr);
        if ( $this->start > $count ) return NULL;

        $end = $this->start + $this->rows;
        $end > $count && $end = $count;

        $temp_arr = array();
        for ( $i = $this->start; $i < $end; $i ++ )
        {
            if ( $media_arr[$i] )
                array_push($temp_arr,$media_arr[$i]);
        }

        return $temp_arr;
    }

    /**
     * 获取指定类型的文件数组
     *
     * @param $type
     * @return null|void
     */
    private function _get_by_type($type) {

        if ( !array_key_exists($type,$this->_type) || !count($this->media_arr) )
        {
            return NULL;
        }

        // 如果指定的type已经存在，则直接返回
        if ( array_key_exists($type, $this->media_arr2type) ) return;

        foreach ( $this->media_arr as $key => $media )
        {
            if ( $type === $media->media_type )
            {
                array_push($this->media_arr2type[$type],$media);
            }
        }

        return;
    }


    /**
     * 获取文件路径
     *
     * @param $type
     * @return bool
     */
    public function get_path ( $type = 'all' ) {
        if ( !array_key_exists($type,$this->_path) )
        {
            return FALSE;
        }

        return $this->_path[$type];
    }


    private function get_media_dir_list ( $path ) {

    }


    /**
     * 根据制定路径，获取下面所有的文件
     * 并封装成对象返回
     *
     * @param $path
     * @return array
     * @throws Exception
     */
    private function get_media_list ( $path ) {

        if ( !$path )
        {
            throw new Exception('fetal error: path can not empty');
        }

        $media_info_arr = get_dir_file_info($path, FALSE);

        $media_arr = array();
        if ( count($media_info_arr) )
        {
            foreach ( $media_info_arr as $key=>$val )
            {
                $media = new \Beans\Media();
                $media->media_name        = $val['name'];
                $media->media_authcode    = authcode2url($val['server_path'],'ENCODE',AUTHCODE_KEY);
                $media->media_size        = $val['size'];
                $media->media_size_count  = $this->get_size_count($val['size']);
                $media->media_create_time = $val['date'];
                $media->media_type        = $this->get_media_type($media->media_name);

                if ( 'image' === $media->media_type )
                {
                    $media->media_width  = file_exists($val['server_path']) ? getimagesize($val['server_path'])[0] : 0;
                    $media->media_height = file_exists($val['server_path']) ? getimagesize($val['server_path'])[1] : 0;
                }

                array_push($media_arr,$media);
            }
        }

        return $media_arr;
    }

    /**
     * 文件大小转换
     *
     * @param $size
     * @return string
     */
    public function get_size_count($size) {
        if($size >= 1073741824) {
            $size = round($size / 1073741824 * 100) / 100 . ' gb';
        } elseif($size >= 1048576) {
            $size = round($size / 1048576 * 100) / 100 . ' mb';
        } elseif($size >= 1024) {
            $size = round($size / 1024 * 100) / 100 . ' kb';
        } else {
            $size = $size . ' bytes';
        }
        return $size;
    }

    /**
     * 获取文件类型
     * @param $media_name
     * @return bool|string
     */
    public function get_media_type($media_name) {
        $suffix = pathinfo($media_name,PATHINFO_EXTENSION);
        //dump($suffix);
        foreach ( $this->_type as $key => $val )
        {
            if ( in_array($suffix,$val) )
            {
                return $key;
            }
        }

        return NULL;
    }

}